<template>
	<div class="goods">
		<van-sticky>
			<van-nav-bar :title="room_info.room_title" 
						 :safe-area-inset-top="true" 
						 :placeholder="true"
						 left-text="返回大厅"
						 right-text="分享"
						 left-arrow
						 @click-left="onClickLeft"
						 @click-right="showShare = true" />
			<van-cell-group>
				<van-cell :label="room_info.current_title">
					<template #title>
						<div>房间号：{{room_info.room_number}}</div>
					</template>
				</van-cell>
			</van-cell-group>
		</van-sticky>
		
		<van-share-sheet v-model="showShare" title="立即分享给好友" :options="options" />
		
		<van-cell-group>
			<van-cell :label="room_info.current_title">
				<van-tabs :sticky="true" 
						  :swipeable="true" 
						  :animated="true" 
						  offset-top="100" 
						  color="#FFD801"
						  v-model="active_tabs_index" >
					<van-tab title="玩家列表">
						<template #title>
							<van-icon name="friends-o" />玩家列表 
						</template>
						<br>
						<tabs-player :roomInfo="room_info" 
									 :playerList="player_list" 
									 :playerInfo="player_info"
									 :IsHasDie="isHasDie"
									 :StartVoting="startVoting"
									 :ThisVote="this_vote"></tabs-player>
					</van-tab>
					<van-tab>
						<template #title> 
							<van-icon name="more-o" />信息/投票流水 
						</template>
						<tabs-flow></tabs-flow>
					</van-tab>
				</van-tabs>
			</van-cell>
		</van-cell-group>
		
		<van-share-sheet v-model="dialogVisible" 
						 title="以下是最终结果" 
						 :options="final_list" 
						 description="获胜人员名单"
						 @cancel="closeDialogVisible()"
						 @click-overlay="closeDialogVisible()" />
		
		<van-goods-action :safe-area-inset-bottom="true">
			<van-goods-action-button v-if="homeowner == true && room_info.room_status == 1"
									 color="linear-gradient(to right, #ff6034, #FFD801)" 
									 text="开始游戏"
									 @click="handleBeing()" />
			<van-goods-action-button v-if="room_info.room_status == 2"
									 color="linear-gradient(to right, #ff6034, #FFD801)" 
									 text="查看卡片"
									 @click="prompt_window(player_info.phrase)" />
			<van-goods-action-button color="#FFD801" 
									 text="打印所有数据" 
									 @click="consoleData()" />
			<van-goods-action-button color="#FFD801" 
									 text="清理缓存数据" 
									 @click="clear_all()" />					 
			<van-goods-action-button v-if="room_info.room_status == 2"
									 color="linear-gradient(to right, #FFD801, #ff6034)" 
									 text="放弃本轮投票"
									 @click="Unreport()" />
		</van-goods-action>
	</div>
</template>

<script>
import Vue from 'vue';
import { GoodsAction,GoodsActionIcon,GoodsActionButton,NavBar,SwipeCell,ShareSheet,Popup } from 'vant';
import tabsPlayer from '../Common/tabsPlayer.vue';
import tabsFlow from '../Common/tabsFlow.vue';

Vue.use(Popup);
Vue.use(GoodsAction);
Vue.use(GoodsActionButton);
Vue.use(GoodsActionIcon);
Vue.use(NavBar);
Vue.use(SwipeCell);
Vue.use(ShareSheet);

export default {
	data() {
		return {
			route_querys:{},
			room_info:{},
			player_info:{},		//手动拼接玩家的信息
			player_list:{},		//由socket返回的所有玩家列表
			voting_info:[],
			socket:'',
			homeowner:false,	//是否是房主
			dialogVisible:false,//最终结果展示框
			isHasDie:false,		//是否死亡（被投票出局）
			this_vote:false,	//是否已经投票
			startVoting:false,	//是否可以投票
			active_tabs_index:0,
			showShare:false,
			final_list: [],		//最终结果
			options: [[
			        { name: '微信', icon: 'wechat' },
			        { name: '微博', icon: 'weibo' },
			        { name: 'QQ', icon: 'qq' },
			    ],[
			        { name: '复制链接', icon: 'link' },
			        { name: '分享海报', icon: 'poster' },
			        { name: '二维码', icon: 'qrcode' },
			        { name: '小程序码', icon: 'weapp-qrcode' },
			    ]],
		}
	},
	created() {
		//接收路由参数
		this.route_querys = this.$route.query;
		//验证房间信息
		this.room_init();
		//获取缓存信息
		this.getLocalStorage();
	},
	methods: {
		onClickLeft() {
			if (this.room_info.room_status == 1){
				//断开连接
				//退出房间 - 返回大厅
				this.$router.push('/game_hall');
			} else {
				this.$toast({ message: '游戏已开具禁止退出', position: 'bottom',duration: 1500 });
			}
		},
		getLocalStorage(){
			//玩家信息
			this.player_info = this.$getCookie('user_info')?JSON.parse(this.$getCookie('user_info')):'';
			//投票信息
			this.this_vote= sessionStorage.getItem('this_vote')?true:false;
			this.isHasDie = sessionStorage.getItem('isHasDie')?true:false;
			//获取投票流水
			//this.voting_info = sessionStorage.getItem('voting_flow');
		},
		room_init(){
			//加载
			let toast = this.$toast.loading({ duration: 0, forbidClick: true, message: '初始化房间...' });
			//发送请求，验证数据库中房间状态
			this.$post('/game/hall/into_room', this.route_querys).then(res => {
				if (res.code == 200 ){
					toast.clear();
					this.messageTips('房间初始化成功','success','notify');
					//拼接
					this.room_info = res.data;
					this.player_info.room_number = this.room_info.room_number;
					//连接websocket
					this.ConnectingToServer();
					/* if(this.judgeRoomInformation(res.data,toast)){
						toast.clear();
						this.messageTips('房间初始化成功','success','notify');
						//拼接
						this.room_info = res.data;
						this.player_info.room_number = this.room_info.room_number;
						//连接websocket
						this.ConnectingToServer();
					} else {
						this.messageTips('验证房间信息失败','error','notify',true);
					} */
				} else {
					this.messageTips(res.msg,'error','notify');
				}
			}).catch((e) => {
				console.log(e);
				this.messageTips('初始化失败，请重新进入房间','error','notify',true);
			});
		},
		judgeRoomInformation(params,toast) {
			//判断房间状态
			if (params.room_status == 0) {
				toast.clear();
				this.$toast({ message: '该房间已被封禁，禁止操作',duration: 1500 });
				return false;
			} else if(params.room_status == 2) {
				toast.clear();
				this.$toast({ message: '该房间游戏已经开始，中途禁止加入',duration: 1500 });
				return false;
			} else {
				//判断房间人数
				if (params.current >= params.room_max) {
					toast.clear();
					this.$toast({ message: '该房间人数已满禁止加入',duration: 1500 });
					return false;
				} else {
					return true;
				}
			}
		},
		ConnectingToServer() {	//连接服务器
			//加载
			let toast = this.$toast.loading({ duration: 0, forbidClick: true, message: '连接服务中...' });
			//定义
			let _this = this;
			//连接
			this.socket = new WebSocket("ws://127.0.0.1:1998");
			//连接失败
			this.socket.onerror = function () { 
				toast.clear();
				_this.messageTips('连接游戏服务Socket失败','error','notify', true);
			};
			//连接成功
			this.socket.onopen = function () {
				toast.clear();
				_this.messageTips('连接游戏服务Socket成功','success','notify');
			};
			//判断消息类型
			this.socket.onmessage = function(e){
				let data = JSON.parse(e.data);
			    let type = data.type || '';
				
			    switch(type){
			        case 'init':		//初始化
						_this.player_info.client_id = data.client_id;
			            // 利用jquery发起ajax请求，将client_id发给后端进行uid绑定
			            _this.$post('/game/room/bind_token', _this.player_info).then(res => {
							if (res.code == 200) {
								_this.player_info = res.data;
							} else {
								_this.messageTips(res.msg,'error','notify', true);
							}
						});
						break;
						
					case 'connect':		//连接成功后进入房间，欢迎信息
						_this.messageTips(data.content,'','toast');
						break;
						
					case 'gamer_list':	//获取本房间内所有玩家列表
						let common_table_info = [];
						for(let i in data.gateway_list){
							common_table_info.push(data.gateway_list[i]);
						}
						_this.player_list = common_table_info;
						//调用分配房主机制方法
						_this.assignHomeowners(common_table_info);
						//刷新房间当前人数
						_this.room_info.current = data.total;
						_this.room_info.current_title = '人数：'+data.total+'/'+_this.room_info.room_max;
						
						_this.this_vote = false;
						//console.log(_this.this_vote);
						break;
					
					case 'identity':	//房主点击开始后分配给自己的身份
						//弹出提示框
						_this.prompt_window(data.data.phrase);
						//开启投票
						_this.startVoting= true;
						//隐藏开始按钮
						_this.homeowner  = false;
						_this.player_info = data.data;
						break;
					
					case 'playerInfo':	//玩家信息，这个是在开始后才会有的东西，有说明我在一个开具的房间内
						//弹出提示框
						_this.prompt_window(data.data.phrase);
						//开启投票
						_this.startVoting= true;
						//隐藏开始按钮
						_this.homeowner  = false;
						_this.player_info = data.data;
						break;
						
					case 'voting_flow':	//接收投票流水	1.unshift()，2.push(),3.splice()
						_this.voting_info.unshift(data.data);
						//存入本地缓存
						sessionStorage.setItem("voting_flow",JSON.stringify(_this.voting_info));
						break;
					
					case 'room_info':	//更新房间状态
						_this.room_info.room_status = 2;
						break;
						
					case 'broadcast':	//接收本轮投票出局玩家信息
						if (data.report == 'report') {
							if (data.data._token == _this.player_info._token) {
								_this.$toast({message:'您已被投票出局',position:'bottom',duration: 1500});
								_this.isHasDie = true;
								//存入本地缓存
								sessionStorage.setItem("isHasDie",true);
							} else {
								_this.$toast({message:data.content,position:'bottom',duration: 1500});
							}
						} else {
							_this.$toast({message:data.content,position:'bottom',duration: 1500});
						}
						
						if(_this.isHasDie === false) {
							_this.this_vote = false;
							sessionStorage.removeItem('this_vote');//本轮是否投票
						}
						break;
						
					case 'final_result':	//接收最终结局
						let winner_lists = [];
						for(let i in data.data.winner_list){
							winner_lists.push(data.data.winner_list[i]);
						}
						_this.final_list[0] = winner_lists;
						
						let failure_lists = [];
						for(let i in data.data.failure_list){
							failure_lists.push(data.data.failure_list[i]);
						}
						_this.final_list[1] = failure_lists;
		
						_this.dialogVisible= true;

						break;
						
					case 'msg':	//接收其他msg类型消息，仅展示提醒不做操作
						_this.$toast({message:data.content,position:'bottom',duration: 1500});
						break;
						
					case 'no_died':	//弃票人数过多没人被投票出局
						_this.$toast({message:data.content,position:'bottom',duration: 1500});
						if(_this.isHasDie === false) {
							_this.this_vote = false;
							sessionStorage.removeItem('this_vote');//本轮是否投票
						}
						break;
						
					case 'signOut':
						_this.$toast({message:data.content,position:'bottom',duration: 1500});
						//data.gateway_list
						break;
						
					case 'ping':	//心跳检测机制
						console.log('check whether it is online!');
						break;
			        default :
						console.log('以下是其他类型信息：');
						console.log(data);
			    }
			};
		},
		handleBeing(){
			//加载
			let toast = this.$toast.loading({ duration: 0, forbidClick: true, message: '请求服务器中...' });
			setTimeout(() => {
				this.$post('/game/room/being_game', this.room_info).then(res => {});
				toast.clear();
			}, 1500);
		},
		Unreport(){
			if(this.isHasDie === true){
				this.messageTips('您已被投票出局，无法操作','','toast');
				return false;
			}
			
			if (this.this_vote){
				this.messageTips('本轮您已投票，请勿重复操作','','toast');
				return false;
			}
			
			this.$dialog.confirm({
				message: '确定要放弃本轮投票机会吗',
				theme: 'round-button',
			}).then(() => {
			    this.$post('/game/server/Unreport', this.player_info).then(res => {
			    	if (res.code == 200) {
			    		this.this_vote = true;
			    		sessionStorage.setItem('this_vote',true);
						
			    		this.messageTips('已经放弃本轮投票','','toast');
			    	} else {
						this.messageTips(res.msg,'','toast');
			    	}
			    })
			}).catch(() => {});
		},
		prompt_window(terms){
			this.$dialog.alert({
				title: '身份卡片',
				message: '您的词语是【'+terms+'】',
				theme: 'round-button',
			}).then(() => {});
			//this.$alert('您的词语是【'+terms+'】', '身份卡片', {confirmButtonText: '确定并隐藏'});
		},
		clear_all(){
			this.$dialog.confirm({
				message: '确定要清除吗',
				theme: 'round-button',
			}).then(() => {
			    sessionStorage.clear();
			}).catch(() => {});
		},
		clear_session(){
			sessionStorage.removeItem('isHasDie');	//是否出局 死亡
			sessionStorage.removeItem('this_vote');	//本轮是否投票
		},
		closeDialogVisible(){
			console.log(1123456)
			//删除缓存
			this.clear_session();
			this.getLocalStorage();
			
			//修改房间状态
			this.room_info.room_status = 1;
			
			this.homeowner 	 = false;
			this.dialogVisible = false;
			//重新分配房主
			this.assignHomeowners(this.player_list);
		},
		assignHomeowners(common_table_info){
			//判断第一位是不是自己 第一位才是房主，显示开始按钮
			let user_token = this.$getCookie('user_token');
			if(common_table_info[0]['_token'] == this.$getCookie('user_token') && this.room_info['room_status'] == 1){
				this.homeowner = true;
			}
		},
		messageTips(msg, msg_type, tips_type='', to_black=false, time=1500){
			if(tips_type == 'notify') {
				if (msg_type == 'success') {
					this.$notify({ type: 'success', message:msg });
				} else if(msg_type == 'error'){
					this.$notify({ type: 'danger', message:msg });
				} else {
					this.$notify({ type: 'warning', message:msg });
				}
				console.log('messageTips.$notify:',msg)
			} else {
				if (msg_type == 'success') {
					this.$toast.success({ message:msg, position: 'bottom', duration:time });
				} else if(msg_type == 'error'){
					this.$toast.fail({ message:msg, position: 'bottom', duration:time });
				} else {
					this.$toast({ message:msg, position: 'bottom', duration:time });
				}
				console.log('messageTips.$toast:',msg)
			}
			//判断是否返回
			if(to_black == true){
				this.$router.push('/game_hall');
			}
		},
		consoleData(){
			console.log(this.$data);
		}
	},
	components: { tabsPlayer,tabsFlow },
};
</script>

<style lang="less" scoped>
	.van-nav-bar {
		background-color:#FFD801;

		/deep/.van-nav-bar__content {
			.van-nav-bar__right {
				.van-nav-bar__text{
					color: white;
				}
			}
			.van-nav-bar__left {
				.van-nav-bar__text{
					color: white;
				}
				.van-icon {
					color: white;
				}
			}
		}
	}
	.van-nav-bar__text {
		color:white;
	}
	
	.goods {
		padding-bottom: 50px;
		&-swipe {
			img {
				width: 100%;
				display: block;
			}
		}
		&-title {
			font-size: 16px;
		}
		&-price {
			color: #f44;
		}
		&-express {
			color: #999;
			font-size: 12px;
			padding: 5px 15px;
		}
		&-cell-group {
			margin: 15px 0;
			.van-cell__value {
				color: #999;
			}
		}
		&-tag {
			margin-left: 5px;
		}
	}
</style>
